package com.myidis.servlet;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.auxiliary.UserListForm;
import com.myidis.entity.Department;
import com.myidis.entity.RightRole;
import com.myidis.entity.User;
import com.myidis.mapper.UserMapper;
import com.myidis.mapper.DeptMapper;
import com.myidis.mapper.RightRoleMapper;
import com.myidis.request.PasswordReq;
import com.myidis.response.UserRes;

@Service
public class UserServlet {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private DeptMapper deptMapper;
	@Autowired
	private RightRoleMapper rightRoleMapper;
	
	public UserListForm form() {
		List<RightRole> roleOption = rightRoleMapper.all();
		List<Department> deptOption = deptMapper.all();
		return new UserListForm(this.all(), roleOption, deptOption);
	}
	
	public List<UserRes> all() {
		return this.useful(userMapper.all());
	}
	
	public List<UserRes> getByDept(int dept) {
		return this.useful(userMapper.getByDept(dept));
	}
	
	public List<UserRes> getByGroup(int group) {
		return this.useful(userMapper.getByGroup(group));
	}
	
	private List<UserRes> useful(List<User> users) {
		List<UserRes> res = new ArrayList<UserRes>();
		for(User user: users) {
			Department dept = deptMapper.getOne(user.getDept());
			RightRole role = rightRoleMapper.getOne(user.getRole());
			res.add(new UserRes(user, dept, role));
		}
		return res;
	}
	
	public User getOne(int id) {
		return userMapper.getOne(id);
	}
	
	public User getByUN(String userName) {
		return userMapper.getByUN(userName);
	}
	
	public int insert(User obj) {
		return userMapper.insert(obj);
	}
	
	public int insertAll(List<User> objs) {
		int count = 0;
		for (User obj: objs) {
			System.out.println(obj.toString());
			count += userMapper.insert(obj);
		}
		return count;
	}
	
	public int update(User obj) {
		obj.setPassword(userMapper.getOne(obj.getId()).getPassword());
		return userMapper.update(obj);
	}
	
	public int pswUpd(PasswordReq req) {
		User user = userMapper.getOne(req.getId());
		if(user.getPassword().equals(req.getOldPsw())) {
			user.setPassword(req.getNewPsw());
			userMapper.pswUpdate(user);
			return 1;
		}
		else
			return -1;
	}
	
	public int delete(int id) {
		return userMapper.delete(id);
	}
	
	public int deleteAll(int[] ids) {
		int count = 0;
		for(int id: ids)
			count += userMapper.delete(id);
		return count;
	}
}
